<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="padding-top: 30px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters" >
        <el-form-item label="选择分组：">
          <el-select v-model="filters.groupId" placeholder="选择分组">
            <el-option v-for="item in statusList" :key="item.id" :label="item.memberTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="邮箱：" label-width="100px">
          <el-input v-model="filters.name" placeholder="邮箱"></el-input>
        </el-form-item>

        <el-row style="text-align: right">
          <el-form-item>
            <kt-button icon="fa fa-search" :label="$t('action.search')" type="primary" @click="findPage(null)"/>
          </el-form-item>
          <el-form-item>
            <kt-button :label="$t('action.reset')" type="primary" @click="resetForm('filters')"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-plus" :label="$t('action.add')" type="primary" @click="handleAdd"/>
          </el-form-item>

          <el-form-item>
            <el-button-group>
              <el-tooltip content="刷新" placement="top">
                <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
              </el-tooltip>

              <el-tooltip content="导出" placement="top">
                <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
              </el-tooltip>
            </el-button-group>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
      ></table-column-filter-dialog>
    </div>

    <!--表格内容栏-->
    <cy-table
      :height="350"
      :data="pageResult"
      v-loading="loading"
      :columns="filterColumns"
      :showBatchDelete="false"
      :showDeleteOperation="true"
      :showSelection="false"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      ref="CyTable"
    ></cy-table>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="45%" :visible.sync="editDialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="size">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="addType">
          <el-radio v-model="dataForm.addType" label="0">单个添加</el-radio>
          <el-radio v-model="dataForm.addType" :disabled="!operation" label="1">批量导入</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" prop="name" v-if="dataForm.addType != 1">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="上传文件" prop="id" v-if="dataForm.addType == 1">
          <el-upload  ref="rebateUpload"
                      action="*"
                      accept=".xls,.xlsx"
                      :on-exceed="handleExceed"
                      :file-list="fileList"
                      :limit="1"
                      :http-request="uploadExcel"
          >
            <el-button icon="el-icon-upload" size="small" type="primary">导入文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属分组" prop="groupName">
          <el-select v-model="dataForm.groupName" placeholder="所属分组" style="width:215px" @change="selectChange">
            <el-option v-for="item in statusList" :key="item.id" :label="item.memberTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remarks" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click.native="submitForm"
                   :loading="editLoading">{{$t('action.submit')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CyTable from "@/views/Core/JicTable";
  import KtButton from "@/views/Core/KtButton";
  import {format, formatWithSeperator} from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import { exportExcel } from "@/utils/excel";
  export default {
    components: {
      CyTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        statusList: [

        ],
        fileList:[],
        file:null,
        size: "small",
        text: '查看',
        disabledBoolean: true,
        filters: {
          name: '',
          groupId:null,
          labelId:this.utils.roster.email,

        },
        optionSex: [{id: 0, name: '男'}, {id: 1, name: '女'}],
        memberTypeList: [],
        columns: [
          {prop: "name", label: "邮箱", minWidth: 100},
          {prop: "groupName", label: "所属分组", minWidth: 100},
          {prop: "updateTime", label: "更新时间", minWidth: 100},
          {prop: "addType", label: "添加方式", minWidth: 100,formatter:function (row) {
              if(row.addType ==0){
                return "单个添加"
              }else {
                return "批量导入"
              }
            }},
          {prop: "creatorName", label: "添加人", minWidth: 80},
          {prop: "remarks", label: "备注", minWidth: 120},
        ],
        filterColumns: [],
        pageRequest: {pageNum: 1, pageSize: 10},
        pageResult: {},
        operation: false, // true:查看, false:编辑
        editDialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        loading: false,
        label:this.utils.roster.email,
        dataFormRules: {
          name: [{required: true, message: "邮箱不能为空", trigger: "blur"}],
          groupName: [{required: true, message: "请选择分组", trigger: "blur"}]
        },
        // 新增编辑界面数据
        groupId:"",
        dataForm: {
          id: "",
          name: "",
          groupName: "",
          labelId:this.utils.roster.email,
          addType: '0',
          remarks: "",
        }
      };
    },
    methods: {
      // 获取分页数据
      findPage: function (data) {
        let this_ = this;
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        if(data != null && data.start != null){
          if(data.start != null){
            this.pageRequest.pageNum = data.start;
          }
          if(data.limit != null){
            this.pageRequest.pageSize = data.limit;
          }
        }

        this_.filters.start = this.pageRequest.pageNum;
        this_.filters.limit = this.pageRequest.pageSize;
        this.loading = true;
        this.utils.request.queryMemberRosterList(this_.filters, function (res) {

          if (res.data.rows == null) {
            res.data.rows = [];
          }
          this_.$refs.CyTable.findPage({content:res.data.rows,total:res.data.total});
          this_.loading = false
        });
      },
      // 显示新增界面
      handleAdd: function () {
        this.editDialogVisible = true;
        this.operation = true;
        this.dataForm = {
          id: "",
          name: "",
          groupName: "",
          labelId:this.utils.roster.email,
          addType: '0',
          remarks: "",
        }
      },

      uploadExcel(item){
        this.file = item.file;
      },
      handleExceed(files) {

        this.file= files[0];
        this.$refs["rebateUpload"].clearFiles(); //清除文件
        this.$refs["rebateUpload"].handleStart(files[0]); //选择文件后的赋值方法
      },


      selectChange:function(id){

        let result = this.statusList.find((item)=>{
          return item.id == id
        })
        this.groupId = result.id
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.editDialogVisible = true;
        this.disabledBoolean = false;
        this.operation = false;
        this.$nextTick(function () {
          this.dataForm = Object.assign({}, params.row);
          this.dataForm.addType =params.row.addType+""
        });
      },

      // 编辑
      submitForm: function () {
        let this_ = this;
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {

              this_.dataForm.groupId = this_.groupId

              if(this_.dataForm.addType =='0'){
                if(this_.operation ){
                  this.utils.request.addMemberRoster(this_.dataForm, function (res) {
                    if (res.code == '0000') {
                      this_.$message({message: "操作成功", type: "success"});
                      this_.editDialogVisible = false;
                      this_.findPage(null)
                    }
                  });
                }else {
                  this.utils.request.updateMemberRoster(this_.dataForm, function (res) {

                    if (res.code == '0000') {
                      this_.$message({message: "操作成功", type: "success"});
                      this_.editDialogVisible = false;
                      this_.findPage(null)
                    }
                  });
                }
              }else {
                this_.submitExcelForm()
              }
            });
          }
        });
      },

      submitExcelForm(){
        let this_ =this;

        if(!this_.file){
          this_.$message({message: '请选择文件', type: 'error'})
          return
        }
        const  form = new FormData();
        form.append("file",this_.file);

        this_.utils.request.importMemberRoster(form,function (res) {

          if (res.code == '0000') {

            let list = res.data;

            let params =[];
            list.forEach(a=>{
              let roster = {
                id: this_.dataForm.id,
                labelId:this_.dataForm.labelId,
                addType: this_.dataForm.addType,
                remarks: this_.dataForm.remarks,
                groupId: this_.dataForm.groupId,
                name:a
              };
              params.push(roster)
            })

            let param = {};
            param.requests = params
            this_.utils.request.addBatchMemMemberRoster(param, function (res2) {
              if (res2.code == '0000') {
                this_.$message({message: "操作成功", type: "success"});
                this_.editDialogVisible = false;
                this_.findPage(null)
              }
            });
          } else {
            this_.$message({message: '批量操作失败' + res.msg, type: 'error'})
          }
        })

      },
      // 时间格式化
      dateFormat: function (row, column, cellValue, index) {
        return format(row[column.property]);
      },
      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
          this.findPage(null);
        }
      },

      queryGroups(){
        let this_ = this;
        this.utils.request.queryMemberAll({}, function (res) {
          if(res.code = "0000"){
            this_.statusList = res.data
          }
        });

      },

      // 处理表格列过滤显示
      initColumns: function () {
        var temp = [];

        $.each(this.columns, function (key, val) {
          temp.push(val);
        });
        this.filterColumns = temp;
      },
      // 删除
      handleDelete: function (data) {
        if (data != null && data.params != null && data.params.length > 0) {
          let this_ = this;
          this.utils.request.deleteMemberRoster(data.params[0], function (res) {
            if (res.code == '0000') {
              this_.$message({message: "操作成功", type: "success"});
              this_.findPage(null)
            }
          });
        }

      },
      //列表下载
      downloadExcel() {
        this.$confirm("确定下载列表文件?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let that = this;
            this.utils.request.queryMemberRosterList(this.filters, function (res) {
              exportExcel(res.data.rows, that.columns, "特殊邮件名单");
            });
          })
          .catch(() => {
          });
      }
    },
    mounted() {
      this.initColumns();
      this.queryGroups();
    }
  };
</script>

<style scoped>

</style>
